from typing import Tuple, Optional
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from sqlalchemy.orm import Session
from app.models.user_model import User
from app.core.security import hash_password, verify_password, create_access_token
from app.schemas.user_schema import UserCreate

class UserService:
    @staticmethod
    def register(db: Session, data: UserCreate) -> Tuple[int, str, Optional[User]]:
        # 返回值: (code, message, user实例 or None)
        try:
            if db.query(User).filter(User.username == data.username).first():
                return 400, "用户名已存在", None

            user = User(**data.dict(exclude={"password"}),
                        password=hash_password(data.password))
            db.add(user)
            db.commit()
            db.refresh(user)
            return 201, "注册成功", user

        except IntegrityError:
            db.rollback()
            return 400, "用户名已存在", None
        except SQLAlchemyError:
            db.rollback()
            return 500, "数据库异常", None
        except Exception:
            db.rollback()
            return 500, "服务器内部错误", None

    @staticmethod
    def authenticate(db: Session, username: str, password: str) -> Tuple[int, str, Optional[str]]:
         # 返回值: (code, message, token or None)
        try:
            user = db.query(User).filter(User.username == username).first()
            if not user or not verify_password(password, user.password):
                return 401, "用户名或密码错误", None
            token = create_access_token(str(user.id))
            return 200, "登录成功", token
        except SQLAlchemyError:
            return 500, "数据库异常", None
        except Exception:
            return 500, "服务器内部错误", None